
clear all
set more off

cd "..\..\Derived Data"

insheet using "censusleaid_01.csv" , comma
save "censusleaid_01.dta", replace 

clear all

foreach x of numlist  40 {
insheet using "dfbartik2001_`x'km.csv", clear
qui compress



*Merge in district-grade-year controls
merge m:1 leaid grade using "NCES_2001_to_merge.dta"
drop if _merge==2
drop _merge district_name state_name ell_2001_district spec_2001_district
*Change race #s to pct
foreach var of varlist male_2001 female_2001 asian_2001 hisp_2001 black_2001 white_2001{
gen pct_`var'=`var'/enroll_2001
drop `var'
}

*Merge in district-year controls
merge m:1 leaid using "NCES_2001_to_merge_district.dta"
drop if _merge==2
drop _merge district_name state_name district_name state_name

* merge acs
merge m:1 leaid using "censusleaid_01.dta"
drop if _merge==2
drop _merge


*Drop a lot of observations if include in `raw' form, so create missing indicator and set missing value equal to mean to not lose observations
foreach var of varlist studentteacher_2001 pct_ell_2001 pct_speced_2001 pct_FRPM_2001{
gen missing_`var'=(`var'==.)
su `var'
replace `var'=r(mean) if `var'==.
}


local fuel coal gas oil renewable

* if missing means no production
foreach m of local fuel{
 
 replace ayproduction2001`m'=0 if ayproduction2001`m'==.
replace annual`m'=0 if annual`m'==.
 replace annual`m'lag=0 if annual`m'lag==.

 *leave outs
 gen total`m'_leaveout`x'km=total`m'- annual`m'
 gen total`m'_leaveout`x'km_lag=total`m'_lag - annual`m'lag
 gen leaveout_growth`m'_`x'=(total`m'_leaveout`x'km-total`m'_leaveout`x'km_lag)/total`m'_leaveout`x'km_lag*100
 gen growth`m'=(total`m'-total`m'_lag)/total`m'_lag*100
 
 

}



gen totalprod_fuel`x'=ayproduction2001coal + ayproduction2001gas+ ayproduction2001oil+ ayproduction2001renewable


local fuel coal gas oil renewable

foreach m of local fuel {


display "`m'"
gen `m'share_`x'=ayproduction2001`m'/totalprod_fuel`x'


}


gen bartikleave_`x'=coalshare_`x'*leaveout_growthcoal_`x' + gasshare_`x'*leaveout_growthgas_`x' + oilshare_`x'*leaveout_growthoil_`x'+ renewableshare_`x'*leaveout_growthrenewable_`x'
gen bartik_`x'=coalshare_`x'*growthcoal + gasshare_`x'*growthgas + oilshare_`x'*growthoil+ renewableshare_`x'*leaveout_growthrenewable


drop if cs_mn_all_lag_cohort==.


*keep leaid year testyear_cal testmonth grade stateabb subject cs_mn_all per* *pct_test cs_mn_all_lag* *all *cohort avgPM* move* *_2001  bartik*
outsheet using "dfbartik2001_`x'kmanalysis.csv",comma replace

}
